<?php

/**
 * Controller_file
 */

class Controller_file extends MyApp {

	public function __construct()
	{

		parent::__construct();


		// 左侧个人文件夹展开
		$folder_left = $this->db->fetchAll("SELECT * FROM `tbl_file_folder` WHERE user_id='{$this->user['user_id']}'");
		$this->tpl->assign("folder_left", $folder_left);

		$this->model->file = YOU::loadModel('file');

	}

	/** 首页 **/
	public function actionIndex()
	{

		$this->tpl->display();
	}

	/** 文件列表页 **/
	public function actionList()
	{
		$s = $this->get->s;
		$file_folder = $this->get->file_folder;

		$where = " WHERE user_id='{$this->user['user_id']}' ";

		if (!empty($s)){
			$where .= " AND file_name LIKE '%{$s}%' ";
			$this->tpl->assign("s", $s);
		}

		switch ($file_folder){
			case "open":
				$where = " where is_open='1' ";
				$this->tpl->assign("folder_title", "共享文件夹");
				break;

			default:
				$file_folder = (int)$file_folder;
				$folder_data = $this->db->fetchRow("SELECT folder_name FROM `tbl_file_folder` WHERE folder_id='{$file_folder}'");

				$this->tpl->assign("folder_title", "私人文件夹 - {$folder_data['folder_name']}");

				$where .= " AND folder_id='{$file_folder}' AND is_open='0' ";
				break;
		}

		// 分页
		YOU::loadLib('page', "", '0');

		$tmp = $this->db->fetchRow("SELECT COUNT(1) AS count FROM `tbl_file` {$where} ");
		$count = $tmp['count'];
		$page_total = ceil($count/PAGE_LIMIT);

		// 当前页
		$p = intval($_GET['p']);
		if ($p == 0){
			$p  = 1;
		}
		if ($p > 1){
			$start = PAGE_LIMIT * ($p-1);
		}else{
			$start = 0;
		}

		$file_lists = $this->db->fetchAll("SELECT * FROM `tbl_file` {$where} ORDER BY file_id DESC LIMIT {$start}, ".PAGE_LIMIT."");
		foreach ($file_lists as $key => $value){

			// 格式化文件大小
			$file_lists[$key]['file_size'] =  $this->model->file->formatBytes($value['file_size']);

			// 格式化时间
			$file_lists[$key]['create_time'] = Helper_time::out($value['create_time']);

			// 文件下载地址
			$file_lists[$key]['file_path'] = "upload/user_file".$value['file_path'];

			// 得到文件目录名
			$file_lists[$key]['folder_name'] = $this->model->file->getFolderName($value['folder_id']);
		}


		$page = new Page(array('total' => $count, 'perpage' => PAGE_LIMIT));
		$page->next_page   = '下一页>';
		$page->pre_page    = '<上一页';
		$page->style_path  = "static/page_style";

		$this->tpl->assign("page", $page->show(4, "yahoo"));

		$this->tpl->assign("type", $type);
		$this->tpl->assign("file_lists", $file_lists);
		$this->tpl->assign("count", $count);
		$this->tpl->assign("file_folder", $file_folder);
		$this->tpl->display("file/file.list.tpl.php");
	}


	/** 文件添加 **/
	public function actionAdd()
	{
		$file_folder = $this->get->file_folder;
		$folder_lists = $this->db->fetchAll("SELECT * FROM `tbl_file_folder` WHERE user_id='{$this->user['user_id']}'");

		$folder_name = $this->model->file->getFolderName($file_folder);
		
		$this->tpl->assign("folder_name", $folder_name);		
		$this->tpl->assign("file_folder", $file_folder);
		$this->tpl->assign("folder_lists", $folder_lists);
		$this->tpl->display("file/file.add.tpl.php");
	}

	/** 文件删除 **/
	public function actionDel()
	{
		$file_id = (int)$this->get->file_id;
		$sql = "DELETE FROM `tbl_file` WHERE file_id='{$file_id}' AND user_id='{$this->user['user_id']}'";
		$this->db->query($sql);

		// 跳转
		Helper_Client::location("删除成功", "index.php?a=file.list");
	}

	/** 文件批量删除 **/
	public function actionDelAll()
	{
		$file_folder = $this->post->f_folder;
		$fids = $this->post->fids;

		if (!empty($fids)){

			$fid = implode(",", $fids);

			$sql = "DELETE FROM `tbl_file` WHERE file_id IN ($fid) AND user_id='{$this->user['user_id']}'";
			$this->db->query($sql);

		}

		// 跳转
		Helper_Client::location("删除成功", "index.php?a=file.list&file_folder={$file_folder}");
	}


	/** 文件复制 **/
	public function actionClone()
	{
		$file_id     = $this->post->file_id;

		$file_data = $this->db->fetchRow("SELECT * FROM `tbl_file` WHERE file_id='{$file_id}' AND user_id='{$this->user['user_id']}'");
		if (!empty($file_data)){

			// 如果文件夹相同则返回
			$info = array(
			"file_name"   => $file_data['file_name'],
			"file_size"   => $file_data['file_size'],
			"file_type"   => $file_data['file_type'],
			"file_path"   => $file_data['file_path'],
			"user_id"     => $this->user['user_id'],
			"status"      => 1,
			"create_time" => date("Y-m-d H:i:s"),
			"update_time" => "0000-00-00 00:00:00",
			);

			$file_folder = $this->post->file_folder;
			switch ($file_folder){
				case "open":
					$info['is_open'] = "1";
					break;
				default:
					$info['folder_id'] = $file_folder;
					break;
			}
			$this->db->do_insert("tbl_file", $info);
		}

		// 跳转到列表
		Helper_Client::location("文件复制成功", "index.php?a=file.list&file_folder={$file_folder}");

	}

	/** 文件转移到其他目录 **/
	public function actionMove()
	{
		$file_id     = $this->post->file_id;
		$file_folder = $this->post->file_folder;

		$file_data = $this->db->fetchRow("SELECT * FROM `tbl_file` WHERE file_id='{$file_id}' AND user_id='{$this->user['user_id']}'");
		if (!empty($file_data)){

			// 如果文件夹相同则返回
			$info = array(
			"update_time" => date("Y-m-d H:i:s"),
			);

			$file_folder = $this->post->file_folder;
			switch ($file_folder){
				case "open":
					$info['is_open'] = "1";
					break;
				default:
					$info['folder_id'] = $file_folder;
					break;
			}

			$this->db->do_update("tbl_file", $info, "file_id='{$file_id}'");
		}else{
			Helper_Client::alert("只能转移自己的文件");
		}

		// 跳转到列表
		Helper_Client::location("文件转移成功", "index.php?a=file.list&file_folder={$file_folder}");


	}



	/** 添加文件夹 不递归 其实是添加虚拟目录  共享文件夹添加虚拟子目录**/
	public function actionFolderList()
	{

		$where = " WHERE user_id='{$this->user['user_id']}' ";

		// 分页
		YOU::loadLib('page', "", '0');

		$tmp = $this->db->fetchRow("SELECT COUNT(1) AS count FROM `tbl_file_folder` {$where} ");
		$count = $tmp['count'];
		$page_total = ceil($count/PAGE_LIMIT);

		// 当前页
		$p = intval($_GET['p']);
		if ($p == 0){
			$p  = 1;
		}
		if ($p > 1){
			$start = PAGE_LIMIT * ($p-1);
		}else{
			$start = 0;
		}

		$folder_lists = $this->db->fetchAll("SELECT * FROM `tbl_file_folder` {$where} ORDER BY folder_id DESC LIMIT {$start}, ".PAGE_LIMIT."");
		foreach ($folder_lists as $key => $value){

			// 文件总数
			$row = $this->db->fetchRow("SELECT COUNT(1) AS count FROM `tbl_file` WHERE folder_id='{$value['folder_id']}' AND user_id='{$this->user['user_id']}'");
			$folder_lists[$key]['file_count'] = (int)$row['count'];
			// 文件总大小
			$row = $this->db->fetchRow("SELECT SUM(file_size) AS count FROM `tbl_file` WHERE folder_id='{$value['folder_id']}' AND user_id='{$this->user['user_id']}'");
			$folder_lists[$key]['file_size'] = (int)$row['count'];
			$folder_lists[$key]['file_size'] = $this->model->file->formatBytes($folder_lists[$key]['file_size']);

		}


		$page = new Page(array('total' => $count, 'perpage' => PAGE_LIMIT));
		$page->next_page   = '下一页>';
		$page->pre_page    = '<上一页';
		$page->style_path  = "static/page_style";

		$this->tpl->assign("page", $page->show(4, "yahoo"));

		$this->tpl->assign("folder_lists", $folder_lists);
		$this->tpl->display("file/file.folderlist.tpl.php");
	}

	/** 添加私人文件夹 **/
	public function actionFolderAdd()
	{
		if ($_POST){

			$folder_name = $this->post->folder_name;

			$info = array(
			"folder_name" => $folder_name,
			"user_id"     => $this->user['user_id'],
			"status"      => 1,
			"create_time" => date("Y-m-d H:i:s"),
			"update_time" => "0000-00-00 00:00:00",
			);
			$this->db->do_insert("tbl_file_folder", $info);


			// 跳转
			Helper_Client::location("添加成功", "index.php?a=file.folderlist");


		}

		$this->tpl->display("file/file.folderadd.tpl.php");
	}

	/** 修改私人文件夹 **/
	public function actionFolderUpdate()
	{

		$folder_id = (int)$this->get->folder_id;
		$folder_data = $this->db->fetchRow("SELECT * FROM `tbl_file_folder` WHERE folder_id='{$folder_id}' AND user_id='{$this->user['user_id']}'");

		if (empty($folder_data)){
			Helper_Client::alert("文件夹不存在");
		}

		if ($_POST){

			$folder_name = $this->post->folder_name;

			$info = array(
			"folder_name" => $folder_name,
			"update_time" => date("Y-m-d H:i:s"),
			);
			$this->db->do_update("tbl_file_folder", $info, "folder_id='{$folder_id}'");

			$refer = $this->post->refer;
			if (!empty($refer)){
				$url = $refer;
			}else{
				$url = "index.php?a=file.folderlist";
			}
			// 跳转
			Helper_Client::location("修改成功", $url);
		}

		$this->tpl->assign("refer", $_SERVER['HTTP_REFERER']);
		$this->tpl->assign("folder_data", $folder_data);
		$this->tpl->display("file/file.folderupdate.tpl.php");
	}

	public function actionFolderDel()
	{

		// 判断是否有文件 确认后跳转到 stay=1

		$folder_id = (int)$this->get->folder_id;

		$sql = "DELETE FROM `tbl_file_folder` WHERE folder_id='{$folder_id}' AND user_id='{$this->user['user_id']}'";
		$this->db->query($sql);

		// 跳转
		Helper_Client::location("删除成功", "index.php?a=file.folderlist");
	}


	/** 修改文件夹 **/


	/** 个人文件夹大小设置 **/

	/** 上传文件 **/
	public function actionUpload()
	{


		// Make sure file is not cached (as it happens for example on iOS devices)
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");

		/*
		// Support CORS
		header("Access-Control-Allow-Origin: *");
		// other CORS headers if any...
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
		exit; // finish preflight CORS requests here
		}
		*/

		// 5 minutes execution time
		@set_time_limit(5 * 60);

		// Uncomment this one to fake upload time
		// usleep(5000);

		$targetDir = UPLOAD_PATH.'/user_file';
		$fdir = "/";
		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds


		// Create target dir
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);
		}

		// Get a file name
		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}

		if (function_exists(finfo_open)){
			$finfo    = finfo_open(FILEINFO_MIME);
			$mimetype = finfo_file($finfo, $_FILES['file']['tmp_name']);
			finfo_close($finfo);

			$ftype = $this->model->file->getMime($mime);
		}else{
			$a = explode(".", $fileName);
			$ftype = $a[count($a)-1];
		}
		/*
		if(!$this->model->file->checkType($ftype, array("ppt", "xls", "xlsx", "docs", "doc", "pdf", "jpg", "png", "gif", "zip", "rar") )){
		die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
		}
		*/



		// 重新命名

		$filePath = $targetDir . $fdir . $fileName;

		// Chunking might be enabled
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


		// Remove old temp files
		if ($cleanupTargetDir) {
			if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
			}

			while (($file = readdir($dir)) !== false) {
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

				// If temp file is current file proceed to the next
				if ($tmpfilePath == "{$filePath}.part") {
					continue;
				}

				// Remove temp file if it is older than the max age and is not the current file
				if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
					@unlink($tmpfilePath);
				}
			}
			closedir($dir);
		}


		// Open temp file
		if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
		}

		if (!empty($_FILES)) {
			if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			}

			// Read binary input stream and append it to temp file
			if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		} else {
			if (!$in = @fopen("php://input", "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		}



		while ($buff = fread($in, 4096)) {
			fwrite($out, $buff);
		}

		@fclose($out);
		@fclose($in);

		// Check if file has been uploaded
		if (!$chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off
			rename("{$filePath}.part", $filePath);


			// 重命名防止文件重名
			$new_dir  = $fdir . date("YmdHis").rand(1111, 9999).".{$ftype}";
			$new_path = $targetDir . $new_dir;
			rename($filePath, $new_path);
			$file_name = $fileName;

			// 取得上传后的路径

			// 写入数据库用户记录
			$info = array(
			"file_name"   => $file_name,
			"file_size"   => $_FILES["file"]["size"],
			"file_type"   => $ftype,
			"file_path"   => $new_dir,
			//"folder_id"   => $folder_id,
			"user_id"     => $this->user['user_id'],
			"status"      => 1,
			"create_time" => date("Y-m-d H:i:s"),
			"update_time" => "0000-00-00 00:00:00",
			);
			switch ($_GET['file_folder']){
				case "open":
					$info['is_open'] = "1";
					break;
				default:
					$info['folder_id'] = $_GET['file_folder'];
					break;
			}

			$this->db->do_insert("tbl_file", $info);


		}




		// 输出
		// Return Success JSON-RPC response
		die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
	}



}

?>